package cn.edu.scnu.rediscluster.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.util.StringUtils;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@ConfigurationProperties("spring.redis.cluster")
public class RedisClusterConfig {
    private List<String> nodes;
    private String password;
    private Integer maxTotal;
    private Integer maxIdle;
    private Integer minIdle;

    @Bean
    @ConditionalOnProperty(prefix = "spring.redis.cluster", name = "password")
    JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setPassword(password);
        return factory;
    }

    @Bean
    public JedisCluster initJedisCluster() {
        Set<HostAndPort> set = new HashSet<>();
        for (String node : nodes) {
            set.add(new HostAndPort(node.split(":")[0], Integer.parseInt(node.split(":")[1])));
        }
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        System.out.println(nodes.get(0));
        System.out.println(password);
        if (StringUtils.isEmpty(password)) {
            return new JedisCluster(set, config);
        } else {
            return new JedisCluster(set, 10000, 1000, 1, password, config);
        }
    }

    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }

    public Integer getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(Integer maxTotal) {
        this.maxTotal = maxTotal;
    }

    public Integer getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
